package com.share.example.spider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.example.spider.mapper.StockMapper;
import com.share.example.spider.model.db.Stock;
import com.share.example.spider.service.IStockService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-07-23
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {
    @Override
    public int saveOrUpdateByCode(List<Stock> list) {
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }

        Set<String> allCode = list.stream().map(e -> e.getCode()).collect(Collectors.toSet());

        //查询数据库
        List<String> exsitCode = baseMapper.selectList(Wrappers.<Stock>query().in("code", allCode)).stream().map(e -> e.getCode()).collect(Collectors.toList());

        //要插入的集合
        List<Stock> insert = list.stream().filter(e -> !exsitCode.contains(e.getCode())).collect(Collectors.toList());

        //入库
        this.saveBatch(insert, 500);

        return 1;
    }

    @Override
    public int saveOrUpdateByCode(Stock stock) {


        //查询数据库
        Stock exsitCode = baseMapper.selectOne(Wrappers.<Stock>query().in("code", stock.getCode()));

        if (exsitCode == null) {
            baseMapper.insert(stock);
        }
        return 1;
    }
}
